<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class Withdraw extends Model
{

    

    

    // 表名
    protected $name = 'withdraw';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'status_text'
    ];
    
	const STATUS_WAIT = 0;
	const STATUS_SUCCESS = 1;
	const STATUS_BACK = 2;
	
	public static $statusList = [
		self::STATUS_SUCCESS => '转帐成功',
		self::STATUS_WAIT => '待转帐',
		self::STATUS_BACK => '已退回'
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}
	
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function code() {
		return $this->belongsTo('collectionCode', 'user_id', 'user_id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 提现
	 * @param $user
	 * @param $amount
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function withdraw($user, $amount) {
		$this->startTrans();
		try {
			$userRes = Db::name('user')
				->where(['id' => $user['id']])
				->setDec('money', $amount);
			
			if(!$userRes) {
				throw new Exception('减少余额出错');
			}
			
			$res = $this->isUpdate(false)
				->save([
					'user_id' => $user['id'],
					'amount' => $amount
				]);
			if(!$res) {
				throw new Exception('添加提现记录出错');
			}
			
			
			$fundsModel = new Funds();
			$fundsRes = $fundsModel->addRecord($user['id'], $amount, $user['money'], $fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_LESS, $fundsModel::TYPE_WITHDRAW);
			
			if(!$fundsRes) {
				throw new Exception('添加资料记录出错');
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	/**
	 * 提现退款
	 * @param $id
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function refund($id) {
		$row = $this->find($id);
		if(!$row) {
			$this->error = '记录不存在';
			return false;
		}
		
		if($row['status'] != self::STATUS_WAIT) {
			$this->error = '非待转帐记录';
			return false;
		}
		
		$this->startTrans();
		try {
			$res = $this->save(['status' => self::STATUS_BACK], ['id' => $id]);
			if(!$res) {
				throw new Exception('更改状态出错');
			}
			
			$user = User::get($row['user_id']);
			$userRes = Db::name('user')
				->where(['id' => $row['user_id']])
				->setInc('money', $row['amount']);
			if(!$userRes) {
				throw new Exception('添加用户余额出错');
			}
			
			
			$fundsModel = new Funds();
			$fundsRes = $fundsModel->addRecord($row['user_id'], $row['amount'], $user['money'],$fundsModel::ACCOUNT_TYPE_BALANCE, $fundsModel::OPE_TYPE_PLUS, $fundsModel::TYPE_WITHDRAE_BACK);
			if(!$fundsRes) {
				throw new Exception('添加资金记录出错');
			}
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
		
	}


}
